var rendererOptions = {
	draggable : true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();

var map;
var isPollutionShowing;
var pollutionGrid;
var city = new google.maps.LatLng(55.9410655, -3.2053836);
var GridColorMap = null;

function loadToolsAndMap() {
	var mapOptions = {
		zoom : 12,
		center : city
	};
	map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	
	google.maps.event.addDomListener(window, "resize", function() {
		var center = map.getCenter();
		google.maps.event.trigger(map, "resize");
		map.setCenter(center);
	});
	
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById('directionsPanel'));

	google.maps.event.addListener(directionsDisplay, 'directions_changed',
			function() {
				computeTotalDistance(directionsDisplay.getDirections());
			});
	google.maps.event.addListener(map, "bounds_changed", function() {
//		hidePollution(true);
	});

	var menuButtons = document.querySelector("#menu-buttons");
	menuButtons.className = "btn-group";
	map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(menuButtons);

	var menuButtonsMap = document.querySelector("#menu-buttons-map");
	menuButtonsMap.className = "btn-group";
	map.controls[google.maps.ControlPosition.TOP_CENTER].push(menuButtonsMap);

	var autocomplete1 = new google.maps.places.Autocomplete(document
			.querySelector("#start-from"));
	var autocomplete2 = new google.maps.places.Autocomplete(document
			.querySelector("#destination"));

}

function doOnLoad(lat, lng, gridId) {
	loadToolsAndMap();
	addButtonListeners();
}

function addButtonListeners() {
	$("#show-directions-pollution-button")
			.click(
					function() {
						if (directionsDisplay.directions) {
							if (GridColorMap) {
								drawPolyLines(directionsDisplay.directions.routes[0].legs[0].steps);
							} else {
								var bounds = map.getBounds();
								$
										.ajax(
												{
													type : "GET",
													url : "data/currentsensorforbounds",
													dataType : "json",
													data : {
														southwest : bounds
																.getSouthWest()
																.toString(),
														northeast : bounds
																.getNorthEast()
																.toString()
													}
												})
										.done(
												function(json) {
													if (json.observations.length === 0)
														alert("No Observation");
													updatePollutionBandColor(json);
													drawPolyLines(directionsDisplay.directions.routes[0].legs[0].steps);
												});

							}
						}
					});

	$("#find-route-button").click(function() {
		$('#find-route-model').modal();
	});

	$("#show-directions-button").click(function() {
		$('#show-directions-model').modal();
	});

	$("#find-route-ok").click(
			function() {
				hidePollution(true);
				removePolyLines();
				directionsDisplay.setMap(map);
				setTimeout(function() {
					calcRoute($("#start-from").val(), $("#destination").val(),
							$("#travel-mode").val());
				}, 0);
			});

	$("#show-pollution-button").click(showPollution);

}

function hidePollution(destroyGridObject) {
	isPollutionShowing = false;
	if (pollutionGrid) {
		for (var i = 0; i < pollutionGrid.length; i++) {
			pollutionGrid[i].setMap(null);
		}
	}
	if (destroyGridObject) {
		GridColorMap = null;
		pollutionGrid = null;
	}
}

function showPollution() {
	if (!isPollutionShowing) {
		isPollutionShowing = true;
		if (!pollutionGrid) {
			// get Pollution Data
			var bounds = map.getBounds();
			$.ajax({
				type : "GET",
				url : "data/currentsensorforbounds",
				dataType : "json",
				data : {
					southwest : bounds.getSouthWest().toString(),
					northeast : bounds.getNorthEast().toString()
				}
			}).done(function(json) {
				if (json.observations.length === 0)
					alert("No Observation");
				createPollutionGrid(json);
			});
		} else {
			for (var i = 0; i < pollutionGrid.length; i++) {
				pollutionGrid[i].setMap(map);
			}
		}
	} else {
		hidePollution();
	}
}

function updatePollutionBandColor(json) {
	GridColorMap = {};
	for (var i = 0; i < json.observations.length; i++) {
		var o = json.observations[i];
		var color = Pollution.aqiColor(o, 1);
		GridColorMap[getGridId(o.latitude, o.longitude)] = color;
	}
}

function createPollutionGrid(json) {
	updatePollutionBandColor(json);
	pollutionGrid = [];
	for (var i = 0; i < json.observations.length; i++) {
		var o = json.observations[i];
		var color = GridColorMap[getGridId(o.latitude, o.longitude)];
		pollutionGrid.push(new google.maps.Rectangle({
			strokeColor : color,
			strokeOpacity : 1,
			strokeWeight : 1,
			fillColor : color,
			fillOpacity : 0.35,
			map : map,
			bounds : new google.maps.LatLngBounds(new google.maps.LatLng(
					o.latitude, o.longitude), new google.maps.LatLng(o.latitude
					+ json.gridSize, o.longitude + json.gridSize))
		}));

	}
}
function calcRoute(origin, destination, travelMode) {
	var request = {
		origin : origin,
		destination : destination,
		travelMode : travelMode || google.maps.TravelMode.DRIVING
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
		}
	});
}

function computeTotalDistance(result) {
	var total = 0;
	var myroute = result.routes[0];
	for (var i = 0; i < myroute.legs.length; i++) {
		total += myroute.legs[i].distance.value;
	}
	total = total / 1000.0;
	document.getElementById('total-distance').innerHTML = total + ' km';
}

function removePolyLines() {
	markerA && markerA.setMap(null);
	markerB && markerB.setMap(null);
	if (lines) {
		for (var i = 0; i < lines.length; i++) {
			lines[i].setMap(null);
		}
	}
}

var markerA = null;
var markerB = null;
var lines = null;
var path;
function drawPolyLines(steps) {
	directionsDisplay.setMap(null);
	path = [];
	for (var i = 0; i < steps.length; i++) {
		for (var j = 0; j < steps[i].path.length; j++) {
			path.push(steps[i].path[j]);
		}
	}
	// console.info(path.length);
	path = new Line().getAllBreakLatLng(path);

	markerA = Util.makeMarker(map, path[0]);
	markerB = Util.makeMarker(map, path[path.length - 1]);

	lines = [];
	for (var i = 0; i < path.length - 1; i++) {
		var p = new google.maps.Polyline({
			path : [ path[i], path[i + 1] ],
			geodesic : true,
			strokeColor : getLineColor(path[i]),
			strokeOpacity : 1.0,
			strokeWeight : 5
		});
		lines.push(p);
		p.setMap(map);
	}
}

function getLineColor(path) {
	return GridColorMap[getGridId(path.lat(), path.lng(), 0, -0.01)];
}
